package com.jack.jetpackapp.expand

import android.app.Activity
import android.view.View

/**
 * 反射获取注解信息
 */
class ViewBinder {
    private var mActivity: Activity? = null
    private var mView: View? = null

    companion object {
        private val instance: ViewBinder by lazy {
            ViewBinder()
        }

        @JvmStatic
        fun get() = instance
    }

    fun init(activity: Activity) {
        mActivity = activity
        bindView()
    }

    fun init(view: View) {
        mView = view
        bindView()
    }

    /**
     * 反射获取注解
     * 1、拿到对应的activity、fragment
     * 2、反射获取所有的属性
     * 3、遍历属性，获取有指定注解的属性
     * 4、找到该view
     * 5、将该view设置给activity、fragment
     */
    fun bindView() {
        val clazz = when {
            mActivity != null -> {
                mActivity?.javaClass
            }
            mView != null -> {
                mView?.javaClass
            }
            else -> null
        }
        clazz?.declaredFields?.forEach { field ->
            val bindView = field.getAnnotation(BindView::class.java)
            bindView?.apply {
                val view = when {
                    mActivity != null -> {
                        mActivity?.findViewById<View>(this.value)
                    }
                    mView != null -> {
                        mView?.findViewById(this.value)
                    }
                    else -> null
                }
                field.isAccessible = true
                if (mActivity != null) {
                    field.set(mActivity, view)
                } else if (mView != null) {
                    field.set(mView, view)
                }
                field.isAccessible = false
            }
        }
    }
}